﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;

namespace Wandering
{
    class DBHelper
    {
        //创建数据库连接字符串constring
        private static readonly string constring = "server=.;database=Blogs;user=sa;pwd=569668";

        //创建数据库连接对象sqlConnecton
        private static readonly SqlConnection sqlConnection = new SqlConnection(constring);



        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static DataTable GetDataTable(string sql)
        {
            sqlConnection.Open();

            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sql,sqlConnection);

            DataTable dt = new DataTable();  //生成表

            sqlDataAdapter.Fill(dt);  //存表

            sqlConnection.Close();

            return dt;  //返回有数据的表

        }

        /// <summary>
        /// 添加、删除、更新数据
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static int InsertOrDeleteOrUpdate(string sql)
        {
            sqlConnection.Open();

            SqlCommand sqlCommand = new SqlCommand(sql,sqlConnection);  //创造命令执行语句的实例

            var res=sqlCommand.ExecuteNonQuery();

            sqlConnection.Close();

            return res;//调用增删改数据的共用方法语句，返回并判断受影响的行数

        }

    }
}
